<template>
  <div class="search-wrap">
    <van-sticky>
      <div class="search-container">
        <van-dropdown-menu class="custom-dropdown-menu" style="width: 80px;">
          <van-dropdown-item v-model="active" :title="currentCategory" :options="options" @change="onChange" />
        </van-dropdown-menu>
        <van-search
          style="flex: 1"
          v-model="keyword"
          show-action
          :placeholder="placeholder"
          shape="round"
          clearable
          @search="onSearch"
        >
          <template #action>
            <div style="color: #1989fa" @click="onClickButton">搜索</div>
          </template>
        </van-search>
      </div>
      <div class="search-tag" v-if="type == 0&&searchKey == 'frameMaterial'">
        <van-tag v-for="item in tagList" @click="onClickTag(item)" plain type="primary" class="list-tag">{{item.label}}</van-tag>
      </div>
    </van-sticky>
    <div class="history-wrap" v-if="!keyword && list.length == 0">
      <div class="history-label">历史记录</div>
      <div class="history-list">
        <span v-for="item in historyList" @click="onClickHistory(item)">{{ item }}</span>
      </div>
    </div>
    <div v-if="keyword || list.length !== 0" style="margin-bottom: 20px;">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="finishedText"
        @load="onLoad"
      >
        <div class="order-item" v-if="type==0" v-for="item in list" :key="item" @click="onClickItem(item)">
          <div class="item-title">款式編號：{{ item.styleNum }}</div>
          <div class="item-desc">SBU：{{ item.sbuNum }}</div>
          <div class="item-desc">品牌：{{ item.customerBrand }}</div>
          <div class="item-desc">客戶編號：{{ item.cumstomerNum }}</div>
        </div>
        <div class="order-item" v-if="type==1" v-for="item in list" :key="item" @click="onClickItem(item)">
          <div class="item-title">大辨編號：{{ item.largeScaleNum }}</div>
          <div class="item-desc">SBU：{{ item.sbuNum }}</div>
          <div class="item-desc">品牌：{{ item.customerBrand }}</div>
          <div class="item-desc">客戶編號：{{ item.cumstomerNum }}</div>
        </div>
        <div class="order-item" v-if="type==2" v-for="item in list" :key="item" @click="onClickItem(item)">
          <div class="item-title">首辨編號：{{ item.firstOrderNum }}</div>
          <div class="item-desc">SBU：{{ item.sbuNum }}</div>
          <div class="item-desc">品牌：{{ item.customerBrand }}</div>
          <div class="item-desc">客戶編號：{{ item.cumstomerNum }}</div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup>

defineOptions({
  name: "OrderSearch",
});

// 自动获取字典
import { useRoute, useRouter } from "vue-router";
import { ref, onMounted, watchEffect } from "vue";
import { getProductStylesList } from '@/api/plmProductStyles';
import { getLargeScaleOrderList } from "@/api/plmLargeScaleOrder";
import { getFirstOrderProcessingList } from "@/api/plmFirstOrderProcessing";
import { useDict } from "@/utils/dictionary.js";
import { showToast } from 'vant';
const router = useRouter();
const route = useRoute();

const styleOptions = [
  { text: '款式編號', value: 0, key: 'styleNum' },
  { text: '客户編號', value: 1, key: 'cumstomerNum' },
  { text: '品牌', value: 2, key: 'customerBrand' },
  { text: '镜架材质', value: 3, key: 'frameMaterial' }
];
const firstOptions = [
  { text: '首辨編號', value: 0, key: 'firstOrderNum' },
  { text: '客户編號', value: 1, key: 'cumstomerNum' },
];
const largeOptions = [
  { text: '大辨編號', value: 0, key: 'largeScaleNum' },
  { text: '客户編號', value: 1, key: 'cumstomerNum' },
];

const type = ref(0);
const keyword = ref('');
const searchKey = ref('');
const placeholder = ref('请搜索');
const OPTION_ENUM = {
  '0': styleOptions,
  '1': largeOptions,
  '2': firstOptions
}

const options = ref([]);
const currentCategory = ref('');
const active = ref(0);
const list = ref([]);
const loading = ref(false);
const finished = ref(true);
const page = ref(1);
const pageSize = ref(20);
const finishedText = ref('');
const tagList = ref([]);
const historyList = ref([]);

watchEffect(() => {
  
});

function onChange(index) {
  const category = options.value[index];
  currentCategory.value = category.text;
  active.value = index;
  searchKey.value = category.key;
}

// function onSearch() {
//   console.log(`搜索关键词: ${this.searchValue}, 当前分类: ${this.currentCategory}`);
//   // 执行搜索逻辑，可以使用当前分类和搜索关键词进行过滤
// }

onMounted(async () => {
  const {
    query: { type: mType },
  } = route;
  type.value = mType;
  options.value = OPTION_ENUM[mType];
  active.value = 0;
  searchKey.value = OPTION_ENUM[mType][0]['key'];
  // placeholder.value = `请输入${PLACE_HOLDER_ENUM[mType]}`

  if (mType == 0) {
    useDict(
        "frameMaterials",
        // "glassFrameCate",
        // "frameCate",
        // "productGender"
    ).then((d) => {
      tagList.value = [...d.frameMaterials];
      // [...d.frameCate];
      // [...d.productGender]
    });
  }
  try {
    historyList.value = JSON.parse(localStorage.getItem('HISTORY_LIST')) || [];
  } catch (error) {
    historyList.value = [];
  }
  
});

function onClickTag(item) {
  console.log('onClickTag======>', item)
  keyword.value = item.label;
  onSearch();
}

function onClickHistory(item) {
  keyword.value = item;
  onSearch();
}

function onSearch() {
  console.log('DP010420-03======>', keyword.value)
  let tempHisList = historyList.value;
  tempHisList.unshift(keyword.value);
  if (tempHisList.length > 20) {
    tempHisList.slice(0, 20);
  }
  tempHisList = [...new Set(tempHisList)];
  historyList.value = tempHisList;
  localStorage.setItem('HISTORY_LIST', JSON.stringify(tempHisList));

  page.value = 1;
  list.value = [];
  finished.value = false;
  getList();
}

function getList() {
  if (type.value == 0) {
    queryProductStylesList();
  } 
  if (type.value == 1) {
    queryLargeScaleOrderList();
  }
  if (type.value == 2) {
    queryFirstOrderProcessingList();
  }
}

function onLoad() {
  if (keyword.value) {
    getList();
  }
}

function onClickItem(e) {
  if (type.value == 0) {
    router.push({ path: '/mobile/productStyleDetail', query: { styleNum: e.styleNum } })
  }
  if (type.value == 1) {
    router.push({ path: '/mobile/largeOrderDetail', query: { largeScaleNum: e.largeScaleNum } })
  }
  if (type.value == 2) {
    router.push({ path: '/mobile/firstOrderDetail', query: {  firstOrderNum: e.firstOrderNum } })
  }
}

async function queryProductStylesList() {
  loading.value = true;
  const res = await getProductStylesList({ page: page.value, pageSize: pageSize.value, [searchKey.value]: keyword.value });
  loading.value = false;
  if (res.code === 0) {
    if (!res.data.list || res.data.list.length == 0) {
      finished.value = true;
      finishedText.value = '没有更多了'
    } else {
      page.value = page.value + 1;
      list.value = list.value.concat(res.data.list || [])
    }
  }
}

async function queryLargeScaleOrderList() {
  loading.value = true;
  const res = await getLargeScaleOrderList({ page: page.value, pageSize: pageSize.value, [searchKey.value]: keyword.value });
  loading.value = false;
  if (res.code === 0) {
    if (!res.data.list || res.data.list.length == 0) {
      finished.value = true;
      finishedText.value = '没有更多了'
    } else {
      page.value = page.value + 1;
      list.value = list.value.concat(res.data.list || [])
    }
  }
}

async function queryFirstOrderProcessingList() {
  loading.value = true;
  const res = await getFirstOrderProcessingList({ page: page.value, pageSize: pageSize.value, [searchKey.value]: keyword.value });
  loading.value = false;
  if (res.code === 0) {
    if (!res.data.list || res.data.list.length == 0) {
      finished.value = true;
      finishedText.value = '没有更多了'
    } else {
      page.value = page.value + 1;
      list.value = list.value.concat(res.data.list || [])
    }
  }
}


</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.search-wrap {
  width: 100vw;
  height: 100%;
  background-color: #fff;
  box-sizing: border-box;

  .search-container {
    padding-top: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .search-tag {
    display: flex;
    flex-direction: row;
    overflow-x: scroll;
    /* 隐藏滚动条 */
    &::-webkit-scrollbar {
        height: 0;
    }
    padding: 0 20px 10px;
    width: 100vw;
    box-sizing: border-box;
    background-color: #fff;

    .list-tag {
      font-size: 12px;
      // color: #666666;
      margin-right: 10px;
      white-space: nowrap;
    }
  }
}

.history-wrap {
  display: flex;
  flex-direction: column;
  padding: 20px;

  .history-label {
    font-size: 12px;
    color: #999999;
    margin-bottom: 20px;
  }

  .history-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    span {
      font-size: 12px;
      color: 12px;
      margin-left: 10px;
      margin-bottom: 8px;
      color: #999999;
    }
  }
}

.order-item {
  background-color: #fff;
  box-shadow: 0.5px 0.5px 1px 1px #eee;
  margin: 10px 16px 0;
  padding: 10px 20px;
  border-radius: 6px;

  .item-title {
    font-size: 14px;
    color: #333;
  }

  .item-desc {
    font-size: 12px;
    color: #666;
    margin-top: 8px;
  }
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: unset !important;
}

</style>
